//
//  OfflineViewController.m
//  FeiYang
//
//  Created by User on 15/10/10.
//  Copyright © 2015年 feiyang. All rights reserved.
//

#import "OfflineViewController.h"
#import "CommentViewController.h"
#import "MyActivities.h"
#import "LoginViewController.h"
#import "ProductsDetailsInsidePagesViewController.h"
@interface OfflineViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSIndexPath * Path;
}
@property (nonatomic,retain)UITableView *myTableView;
@property (nonatomic, assign)int idx;
@property (nonatomic,assign) int n;
@property(nonatomic,strong) UIView *noNet;//无网无数据提示
@property(nonatomic,strong) UIView *noDataView;
@property(nonatomic,strong)  NSMutableArray *dataSourceArr;

@property(nonatomic,strong)  NSMutableArray *evaluatedSourceArr;//已经评价过的数组

@property(nonatomic,strong)  NSMutableArray *noEvaluatedSourceArr;//未评价过的数组
@end

@implementation OfflineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"我的活动"];
    [self.view addSubview:topView];

    self.view.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 20.0f, 44.0f, 44.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
    
    [self layoutTableview];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_myTableView.header beginRefreshing];
    self.tabBarController.tabBar.hidden = TRUE;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = FALSE;
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"账号在另一台机器登录，请重新登录!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
#pragma mark------------alertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //删除token等用户数据
    [AccountTools exitLogin];
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    loginViewCon.backBtHide = FALSE;
    [self presentViewController:loginViewCon animated:TRUE completion:^{
        
        [self.navigationController popViewControllerAnimated:FALSE];
        
    }];
    
}


- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self.navigationController popViewControllerAnimated:YES];
}

//刷新表
-(void)refreshTheProjectTableView
{
    
    _idx = 0;
    _n = 0;
    [self getHttpData];
}

//加载更多数据
- (void)AddtoTheProjectTableView
{
    [self getHttpData];
}
- (void)getHttpData
{
    _noDataView.hidden = TRUE;
    _noNet.hidden = TRUE;
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    if (!_noEvaluatedSourceArr) {
        _noEvaluatedSourceArr = [NSMutableArray array];
    }
    
    if (!_evaluatedSourceArr) {
        _evaluatedSourceArr = [NSMutableArray array];
    }


    _n++;
    
//    [[AnimationIndicator sharedIndicator]startAnimation];

    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1],@"token":[[NSUserDefaults standardUserDefaults]objectForKey:@"token"] };
    [AppGlobalClass PostDataWithNSstring:GETUSERTAKEPARTACTIVITIES withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
           
            [_myTableView.header endRefreshing];
            [_myTableView.footer setState:MJRefreshStateIdle];
            [_myTableView.footer endRefreshing];
            
            
            if(_idx == 0)
            {
                [_dataSourceArr removeAllObjects];
                [_evaluatedSourceArr removeAllObjects];
                [_noEvaluatedSourceArr removeAllObjects];
                
            }
            
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray firstObject];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                    MyActivities *activities = [[MyActivities alloc]initWithDictionary:[listArray objectAtIndex:i]];
                    NSString *areScore = [NSString stringWithFormat:@"%@",activities.areScore];
                    if ([areScore isEqualToString:@"0"]) {
                        //没有评价过
                        [_noEvaluatedSourceArr addObject:activities];
                    }else{
                        //已经评价过
                        [_evaluatedSourceArr addObject:activities];
                    }
                    
                    
                }
                
                [_dataSourceArr addObject:_evaluatedSourceArr];
                [_dataSourceArr addObject:_noEvaluatedSourceArr];
                
                _idx++;
                
                [_myTableView reloadData];
                
                if(listArray.count < 10)
                {
                    [_myTableView.footer endRefreshingWithNoMoreData];
                }
                else
                {
                    if (_n<2) {
                        _myTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheProjectTableView)];
                        
                    }
                    
                }
            }
            else
            {
                if (self.dataSourceArr.count==0) {
                    self.noDataView.hidden = FALSE;
                     [_myTableView reloadData];
                    
                }
                
                [self.myTableView.footer endRefreshingWithNoMoreData];
            }
        }
        
    } failure:^(NSError *error){
        [_myTableView.header endRefreshing];
        [_myTableView.footer setState:MJRefreshStateIdle];
        [_myTableView.footer endRefreshing];
        
        _noDataView.hidden = FALSE;
        [_dataSourceArr removeAllObjects];
        [_evaluatedSourceArr removeAllObjects];
        [_noEvaluatedSourceArr removeAllObjects];
        [_myTableView reloadData];
        
        
    } networkerror:^(NSString *networkerror){
        
        _noNet.hidden = FALSE;
        [_dataSourceArr removeAllObjects];
        [_evaluatedSourceArr removeAllObjects];
        [_noEvaluatedSourceArr removeAllObjects];
        [_myTableView reloadData];
        [_myTableView.header endRefreshing];
        [_myTableView.footer setState:MJRefreshStateIdle];
        [_myTableView.footer endRefreshing];
       
    }];
}
//没网提示
#pragma mark - 没网提示
-(UIView *)noNet
{
    if (!_noNet) {
        _noNet = [[UIView alloc]initWithFrame:CGRectMake((_myTableView.frame.size.width-200)/2, (_myTableView.frame.size.height-200)/2, 200, 235)];
        _noNet.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(45, 23, 110, 110);
        [button setImage:[UIImage imageNamed:@"img_nonetwork"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 44, 200, 44)];
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:@"加载失败\n请检查手机是否联网"];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.098 alpha:1.000],
                                 } range:NSMakeRange(0, 5)];
        
        [aString addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12],
                                 NSForegroundColorAttributeName:[UIColor colorWithWhite:0.702 alpha:1.000],
                                 } range:NSMakeRange(5, 9)];
        [label setAttributedText:aString];
        [_noNet addSubview:label];
        [_noNet addSubview:button];
        
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"重新加载" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_noNet addSubview:btn];

    }

    return _noNet;
}

-(UIView *)noDataView{
    if (!_noDataView) {
        
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake((_myTableView.frame.size.width-200)/2, (_myTableView.frame.size.height-200)/2, 200, 235)];
        _noDataView.hidden = TRUE;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(45, 45, 110, 110);
        [button setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(noResultButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 200 - 44, 200, 44)];
        label.text = @"暂无数据";
        label.textAlignment = NSTextAlignmentCenter;
        label.numberOfLines = 0;
        label.font = [UIFont systemFontOfSize:14.0f];
        label.textColor = [UIColor colorWithWhite:0.000 alpha:0.540];
        [_noDataView addSubview:label];
        [_noDataView addSubview:button];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = CGRectMake(60, 210, 80, 25);
        btn.backgroundColor = [UIColor colorWithWhite:0.200 alpha:1.000];
        btn.layer.cornerRadius = 6;
        btn.layer.masksToBounds = YES;
        [btn setTitle:@"点击返回" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataView addSubview:btn];

    }
    
    return _noDataView;
}

- (void)noResultButtonAction:(id)sender
{
    [self refreshTheProjectTableView];
}

- (void)layoutTableview
{
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(16.0f ,64.0f,SCREEN_WIDTH-32.0f ,SCREEN_HEIGHT-64.0f) style:UITableViewStyleGrouped];
    self.myTableView.backgroundColor = [UIColor clearColor];
    self.myTableView.showsVerticalScrollIndicator = NO;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.bounces = TRUE;
    _myTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheProjectTableView)];
    [self.view addSubview:self.myTableView];
    [_myTableView addSubview:self.noDataView];
    [_myTableView addSubview:self.noNet];
    
}

#pragma mark -  tableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   
    return _dataSourceArr.count;
   
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        
        return _evaluatedSourceArr.count;
    }else{
       
        return _noEvaluatedSourceArr.count;
    }
    
    
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        
        UIView * separtor = [[UIView alloc]init];
        separtor.backgroundColor =  kColorGraySperator;
        separtor.tag = 111;
        [cell.contentView addSubview:separtor];//分割线
        
        
        UILabel *mainLabel = [[UILabel alloc]init];
        mainLabel.tag = 1;
        mainLabel.font = [UIFont systemFontOfSize:16.0f];
        mainLabel.textColor = kColorTEXT;
        [cell.contentView addSubview:mainLabel];
        
        
        UILabel *detailLabel = [[UILabel alloc]init];
        detailLabel.font = [UIFont systemFontOfSize:16.0f];
        detailLabel.tag = 2;
        detailLabel.textColor = kColorTEXT;
        
       
        [cell.contentView addSubview:detailLabel];

        if (indexPath.section==1) {
        
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(detailLabelTapGesture:)];

        [detailLabel addGestureRecognizer:gesture];
        
        }
        
        
    }
    
    UIView *separtor = (UIView*)[cell.contentView viewWithTag:111];
    
    
    UILabel *mainLabel = (UILabel*)[cell.contentView viewWithTag:1];
    UILabel *detailLabel = (UILabel*)[cell.contentView viewWithTag:2];
    
    
    if (indexPath.section==0) {
       
        MyActivities *activities =  [[_dataSourceArr objectAtIndex:0]objectAtIndex:indexPath.row];
        CGFloat height1 = [UILabel height:activities.title widthOfFatherView:SCREEN_WIDTH - 100-32 textFont:[UIFont systemFontOfSize:16]];
        
        mainLabel.frame = CGRectMake(24.0f,10.0 ,SCREEN_WIDTH - 100-32,height1 );
        
        mainLabel.numberOfLines = 0;
        detailLabel.text =  [NSString stringWithFormat:@"%@分",activities.avgScore];
        mainLabel.text = [NSString stringWithFormat:@"%@",activities.title];
        detailLabel.textColor = kColorTEXT;
        detailLabel.userInteractionEnabled = NO;
        separtor.frame =   CGRectMake(0.0f, height1+20.0f-0.5f, SCREEN_WIDTH - 32.0f, 0.5);
        
        detailLabel.frame = CGRectMake(NW(mainLabel)+10.0f, 16.0f, 100.0f, 28.0f);
        if (indexPath.row == _evaluatedSourceArr.count-1) {
            separtor.hidden = YES;
        }else{
            separtor.hidden = NO;
        }
        
    }else{
        
        Path = indexPath;
        detailLabel.text = @"去评价";
        detailLabel.textColor = [UIColor redColor];
         detailLabel.userInteractionEnabled = YES;
        MyActivities *activities =  [[_dataSourceArr objectAtIndex:1]objectAtIndex:indexPath.row];
        CGFloat height1 = [UILabel height:activities.title widthOfFatherView:SCREEN_WIDTH - 100-32 textFont:[UIFont systemFontOfSize:16]];
        mainLabel.frame = CGRectMake(24.0f,10.0 ,SCREEN_WIDTH - 100-32,height1 );
        
        mainLabel.numberOfLines = 0;

        mainLabel.text = [NSString stringWithFormat:@"%@",activities.title];
        
         separtor.frame =   CGRectMake(0.0f, height1+20.0f-0.5f, SCREEN_WIDTH - 32.0f, 0.5);
         detailLabel.frame = CGRectMake(NW(mainLabel)+10.0f, 16.0f, 100.0f, 28.0f);
        if (indexPath.row == _noEvaluatedSourceArr.count-1) {
            separtor.hidden = YES;
        }else{
            separtor.hidden = NO;
        }

    }
    

    return cell;
    
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * backView = [[UIView alloc]init];
    backView.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    return backView;

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 0;
    }
    return 8.0f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 8.0f;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * backview = [[UIView alloc]init];
    backview.backgroundColor = [UIColor hexStringToColor:@"#f3f3f3"];
    return backview;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        MyActivities *activities =  [[_dataSourceArr objectAtIndex:0]objectAtIndex:indexPath.row];
        CGFloat height1 = [UILabel height:activities.title widthOfFatherView:SCREEN_WIDTH - 100-32 textFont:[UIFont systemFontOfSize:16]];
        
        return height1+20.0f;
    }else{
         MyActivities *activities =  [[_dataSourceArr objectAtIndex:1]objectAtIndex:indexPath.row];
        CGFloat height2 = [UILabel height:activities.title widthOfFatherView:SCREEN_WIDTH - 100-32 textFont:[UIFont systemFontOfSize:16]];
        
        return height2+20.0f;
    }
    

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MyActivities *activities;
    if (indexPath.section==0) {
        activities =  [[_dataSourceArr objectAtIndex:0]objectAtIndex:indexPath.row];
        
    }else{
       activities =  [[_dataSourceArr objectAtIndex:1]objectAtIndex:indexPath.row];
       
        
    }

    ProductsDetailsInsidePagesViewController *productDetailInsidePagesVC = [[ProductsDetailsInsidePagesViewController alloc]init];
    productDetailInsidePagesVC.navTitle = activities.title;
    productDetailInsidePagesVC.activitesTypeId = activities.activitiesId;
    productDetailInsidePagesVC.valid = [NSString stringWithFormat:@"%@",@"0"];
    [self.navigationController pushViewController:productDetailInsidePagesVC animated:YES];
    
    
}

- (void)detailLabelTapGesture:(id)sender
{
    //去评价
     MyActivities *activities =  [_noEvaluatedSourceArr objectAtIndex:Path.row];
    CommentViewController *commentVC = [[CommentViewController alloc]init];
    commentVC.takePartId =activities.takePartId;
    commentVC.titleStr = activities.title;
    [self.navigationController pushViewController:commentVC animated:YES];
    
}

@end
